package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.basic.web.repository.BusinessRepository;
import com.tarena.lbs.basic.web.repository.CategoryRepository;
import com.tarena.lbs.basic.web.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.attach.param.PicUpdateParam;
import com.tarena.lbs.pojo.basic.param.BusinessParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.BusinessCategoryPO;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import com.tarena.lbs.pojo.basic.vo.BusinessCategoryVO;
import com.tarena.lbs.pojo.basic.vo.BusinessVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BusinessService {
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private AdminRepository adminRepository;


    public List<BusinessCategoryVO> getCategory() {
        List<BusinessCategoryPO> pos = categoryRepository.list();
        List<BusinessCategoryVO> vos = new ArrayList<>();
        if (pos != null && pos.size() > 0){
            vos = pos.stream().map(po -> {
                BusinessCategoryVO vo = new BusinessCategoryVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        return vos;
    }

    public PageResult<BusinessVO> getBusinessInfo(BusinessQuery query) throws BusinessException {
        PageResult<BusinessVO> pageVO = new PageResult<>(query.getPageSize(), query.getPageNo());
        //2.获取登录用户角色
        UserPrinciple userPrinciple = getUserPrinciple();
        //2.1  如果是shop角色，读取admin详情，获取businessId
        if (userPrinciple.getRole()==Roles.SHOP){
            //说明请求用户为商家管理员
            AdminPO adminPO = adminRepository.getById(userPrinciple.getId());
            Asserts.isTrue(adminPO==null,new BusinessException("-2","商家账号不存在"));
            Integer businessId = adminPO.getBusinessId();
            query.setBusinessId(businessId);
        }
        PageInfo<BusinessPO> pageInfoPOS = pageHelperGetInfo(query);
        pageVO.setTotal(pageInfoPOS.getTotal());
        List<BusinessPO> pos = pageInfoPOS.getList();
        List<BusinessVO> vos = new ArrayList<>();
        if (pos != null && pos.size() > 0){
            vos = pos.stream().map(po->{
                BusinessVO vo = new BusinessVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        pageVO.setObjects(vos);
        return pageVO;
    }

    private PageInfo<BusinessPO> pageHelperGetInfo(BusinessQuery query) {
        PageHelper.startPage(query.getPageNo(),query.getPageSize());
        QueryWrapper<BusinessPO> queryWrapper = generateWrapper(query);
        List<BusinessPO> pos = businessRepository.list(queryWrapper);
        PageInfo<BusinessPO> pageInfo = new PageInfo<>(pos);
        return pageInfo;
    }

    private UserPrinciple getUserPrinciple() throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户解析失败"));
        return userPrinciple;
    }

    private QueryWrapper<BusinessPO> generateWrapper(BusinessQuery query) {
        QueryWrapper<BusinessPO> queryWrapper = new QueryWrapper<>();
        if (query.getBusinessName() != null && query.getBusinessName().length() > 0){
            queryWrapper.like("business_name",query.getBusinessName());
        }
        if (query.getBusinessHeadPhone() != null && query.getBusinessHeadPhone().length() > 0){
            queryWrapper.eq("business_head_phone",query.getBusinessHeadPhone());
        }
        if (query.getBusinessStatus() != null){
            queryWrapper.eq("business_status",query.getBusinessStatus());
        }
        if (query.getStartingTime() != null){
            queryWrapper.gt("entry_time",query.getStartingTime());
        }
        if (query.getEndTime() != null){
            queryWrapper.lt("entry_time",query.getEndTime());
        }
        if (query.getBusinessId() != null){
            queryWrapper.eq("id",query.getBusinessId());
        }
        return queryWrapper;
    }

    public void save(BusinessParam businessParam) throws BusinessException {
        //1.校验角色
        checkRole(Roles.ADMIN);
        //2.检查商家信息是否重复提交
        checkRepeat(businessParam.getBusinessName());
        //3.完成入参到po的转化，并保存数据
        BusinessPO po = param2po(businessParam);
        businessRepository.save(po);
        //4.调用其他服务完成图片和商家信息的绑定
        bindImages(po);
    }

    @DubboReference
    private AttachApi attachApi;

    private void bindImages(BusinessPO businessPO) {
        //1.创建一个List<PicUpdateParam>，用于包装方法入参
        List<PicUpdateParam> list = new ArrayList<>();
        //2.包装logo的图片更新对象
        PicUpdateParam logoParam = new PicUpdateParam();
        logoParam.setBusinessId(businessPO.getId());
        logoParam.setBusinessType(100);
        String logoUrl = generateFileUuid(businessPO.getBusinessLogo());
        logoParam.setFileUuid(logoUrl);
        //3.包装license的图片更新对象
        PicUpdateParam licenseParam = new PicUpdateParam();
        licenseParam.setBusinessId(businessPO.getId());
        licenseParam.setBusinessType(200);
        String licenseUrl = generateFileUuid(businessPO.getBusinessLicense());
        licenseParam.setFileUuid(licenseUrl);
        //4.包装list对象
        list.add(logoParam);
        list.add(licenseParam);
        attachApi.batchUpdateBusiness(list);
    }

    private String generateFileUuid(String url) {
        return url.substring(url.lastIndexOf("/")+1);
    }

    private BusinessPO param2po(BusinessParam businessParam) {
        BusinessPO businessPO = new BusinessPO();
        BeanUtils.copyProperties(businessParam,businessPO);
        businessPO.setBusinessStatus(1);
        businessPO.setEntryTime(new Date());
        businessPO.setAuditRemarks("审核通过！");
        return businessPO;
    }

    private void checkRepeat(String businessName) throws BusinessException {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("business_name",businessName);
        long count = businessRepository.count(queryWrapper);
        Asserts.isTrue(count > 0,new BusinessException("-2","商家名称已经存在，不能重复提交！"));
    }

    private void checkRole(Roles role) throws BusinessException {
        //1.获取上游传入的登录用户信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null,new BusinessException("-2","用户解析失败！"));
        Roles userRole = userPrinciple.getRole();
        Asserts.isTrue(role != userRole,new BusinessException("-2","只有平台管理员才有增加商家权限！"));
    }
}
